package test;

import java.awt.BorderLayout;
import java.awt.Image;
import java.awt.image.BufferedImage;
import java.io.BufferedInputStream;
import java.io.BufferedReader;
import java.io.ByteArrayInputStream;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.Iterator;

import javax.imageio.ImageIO;
import javax.imageio.ImageReader;
import javax.imageio.stream.FileImageInputStream;
import javax.imageio.stream.ImageInputStream;
import javax.imageio.stream.ImageInputStreamImpl;
import javax.swing.ImageIcon;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;

public class FastImageRead {

	/**
	 * @param args
	 */
	//public static void main(String[] args) {
	//	new TestReader();
	//}

	public static void main(String[] args) {
		
        String requestUrl = "http://localhost:8090/?action=stream";
        
        if (args.length > 0) {
        	requestUrl = args[0];
        }
        URL url;
        InputStream istream = null;
		try {
			url = new URL(requestUrl.toString());
			HttpURLConnection connection = (HttpURLConnection)url.openConnection();
			System.out.println(connection.getContentType());
			istream = connection.getInputStream();
		} catch (MalformedURLException e) {
		} catch (IOException e) {
		}
        
		
        Image image = null;
        
        /*
            URL url;
            InputStream istream = null;
			try {
				url = new URL(requestUrl.toString());
				istream = url.openStream();
			} catch (MalformedURLException e) {
			} catch (IOException e) {
			}
            
            //BufferedReader in = new BufferedReader(new InputStreamReader(istream));
           */
            double duration = 0.;
            
            for (int i = 0; i < 100; i++) {
            	final long startTime = System.nanoTime();
            	final long endTime;
            	try {
            		image = readImage(istream);
            	} finally {
            		endTime = System.nanoTime();
            	}
            	duration += (endTime - startTime)/1000000.;
            }
            
			System.out.println(duration/100.);
            
			/*
        	JFrame frame = new JFrame();
        	JPanel panel = new JPanel();
        	JLabel label = null;
        	if (image != null) {
        		label = new JLabel(new ImageIcon(image));
        		frame.getContentPane().add(panel, BorderLayout.CENTER);
        		panel.add(label);
        		frame.setSize(640, 480);
        		frame.pack();
        		frame.setVisible(true);
        		frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        	}
            */
            //in.close();
            
    }
	
	public static String readLine(InputStream istream) throws Exception {
		String line = "";
		int readByte;
		while ((readByte = istream.read()) != 13) {
			if (readByte < 0) {
				throw (new IOException());
			}
    		line += (char) readByte;
    	}
    	istream.read();
		
    	return line;
	}
	
	public static BufferedImage readImage(InputStream istream) {
		try {
			int count = 0;
			int bytesRead;
			BufferedImage image = null;
	        int length;
	        String line = "";
	        byte[] byteArray;
	        InputStream in;
	        boolean start = false;
	        	
				while (!start) {
					count++;
	        		line = readLine(istream);
	            	if (line.equalsIgnoreCase("--boundarydonotcross")) {
	            		start = true;
	            	}
	            }
	        	
	        	// Read content type line
	        	line = readLine(istream);
	        	//System.out.println(line);
	        	
	        	// Read data size line
	        	line = readLine(istream);
	        	//System.out.println(line);
	            length = Integer.parseInt(line.split(" ")[1]);
	            //System.out.println("Image size: " + length);
	            
	            
	            // X-timestamp line
	            //line = readLine(istream);
	            //System.out.println(line);
	            // Read empty line
	            line = readLine(istream);
	            //System.out.println(line);
	            
	            // Read image bytes
	            // No all bytes are necessarily ready when the stream is
	            // being read and the while loop ensures that all bytes
	            // will be read
	            bytesRead = 0;
	            byteArray = new byte[length];
	            while (bytesRead < length) {
	            	if (istream.available() > 0) {
	            		byteArray[bytesRead++] = (byte) istream.read();
	            	}
	            }
	            
	            // Read empty line
	            //line = readLine(istream);
            	in = new ByteArrayInputStream(byteArray);
    	        image = ImageIO.read(in);
			return image;
		} catch (Exception e) {
			return null;
		}
	}
}
